package com.beta.backend.gateway.resolver;

import com.beta.backend.gateway.config.GatewayCfgBean;
import com.beta.backend.gateway.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * @author gwqin
 * @description 用户标识解析器，用于识别用户，在限流开启时使用
 * @date 2022-12-06 14:19
 */
@Slf4j
@Component(value = "userKeyResolver")
public class UserKeyResolver implements KeyResolver {

    private static final String BJWT = "bjwt";

    private static final String USERID = "userId";

    @Autowired
    private GatewayCfgBean gatewayCfgBean;

    @Override
    public Mono<String> resolve(ServerWebExchange exchange) {
        return Mono.just(getUserId(exchange));
    }

    public String getUserId(ServerWebExchange exchange) {
        ServerHttpRequest req = exchange.getRequest();
        HttpHeaders httpHeaders = req.getHeaders();

        String secret = null;
        String channel = httpHeaders.getFirst("channel");
        if (StringUtils.equals(channel, "WEIXIN")) {
            secret = gatewayCfgBean.getMpJwtSecret();
        } else if (StringUtils.equals(channel, "QIWEI")) {
            secret = gatewayCfgBean.getJwtSecret();
        } else {
            return StringUtils.EMPTY;
        }

        // 从bjwt中解析用户id，限流的维度为用户id
        String bjwt = httpHeaders.getFirst(BJWT);
        Map<String, String> map = JwtUtil.decrypt(secret, bjwt);
        String userId = map.get(USERID);
        return userId;
    }
}
